package com.isoft.service.impl;

import com.isoft.entity.DfmeCklsEntity;
import com.isoft.mapper.DfmeCklsMapper;
import com.isoft.service.DfmeCklsService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeCklsServiceImpl implements DfmeCklsService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeCklsServiceImpl.class);

    @Autowired
    private DfmeCklsMapper dfmeCklsMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-CKLS XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeCklsEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeCklsEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeCklsEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-CKLS XML structure");
            }

            processFlightData(entity);

            return "DFME-CKLS data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-CKLS XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-CKLS XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeCklsEntity entity) {
        // 插入元数据
        dfmeCklsMapper.insertMeta(entity);

        // 插入航班基础信息
        try {
            dfmeCklsMapper.insertFlightBase(entity);
        } catch (org.springframework.dao.DataIntegrityViolationException ex) {
            if (ex.getMessage() != null && ex.getMessage().contains("唯一性约束")) {
                logger.warn("DFME-CKLS 航班ID已存在，跳过插入: {}", entity.getDflt().getFlightId());
                return;
            } else {
                throw ex;
            }
        }

        // 插入值机柜台信息
        if (entity.getDflt().getCkls() != null) {
            dfmeCklsMapper.insertCheckinCounter(entity);

            // 插入具体的柜台分配信息
            if (entity.getDflt().getCkls().getCounters() != null &&
                    !entity.getDflt().getCkls().getCounters().isEmpty()) {
                dfmeCklsMapper.insertCounters(entity);
            }
        }
    }
}
